package com.hema.auction.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.reyun.sdk.TrackingIO;
import com.hema.auction.R;
import com.hema.auction.base.BaseActivity;
import com.hema.auction.bean.ProfileInfo;
import com.hema.auction.bean.SysUnits;
import com.hema.auction.event.GoShoppingEvent;
import com.hema.auction.event.NoticeDataEvent;
import com.hema.auction.event.TabIndexEvent;
import com.hema.auction.fragment.GoodsFragment;
import com.hema.auction.fragment.IndexFragment;
import com.hema.auction.fragment.MyFragment;
import com.hema.auction.fragment.NewsFragment;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.UrlManager;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.http.biz.UpdateManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.Utils;
import com.hema.auction.widget.view.TabView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 主界面
 * author by john
 */
public class MainActivity extends BaseActivity {

    /**
     * 上一次界面onSaveInstanceState之前的tab被选中的状态key和value
     */
    private static final String TAB_SELECTED = "tab_selected";
    private int indexSelected = 0;
    public static final int TAB_INDEX = 0;
    public static final int TAB_NEWS = TAB_INDEX + 1;
    public static final int TAB_GOODS = TAB_NEWS + 1;
    public static final int TAB_MY = TAB_GOODS + 1;

    /**
     * Fragment的TAG 用于解决app内存被回收之后导致的fragment重叠问题
     */
    private static final String[] FRAGMENT_TAG = {
            IndexFragment.class.getSimpleName(),
            NewsFragment.class.getSimpleName(),
            GoodsFragment.class.getSimpleName(),
            MyFragment.class.getSimpleName()};

    private TabView lastTab;// 上次选中的tab
    @BindView(R.id.tab_index)
    public TabView tabIndex; // 主页
    @BindView(R.id.tab_news)
    public TabView tabNews; // 最新揭晓
    @BindView(R.id.tab_goods)
    public TabView tabGoods; // 商品分类
    @BindView(R.id.tab_my)
    public TabView tabMy; // 我的

    @BindView(R.id.iv_ad)
    ImageView ivBack;//不中包赔

    private FragmentManager fragmentManager;
    private IndexFragment indexFragment;
    private NewsFragment newsFragment;
    private GoodsFragment goodsFragment;
    private MyFragment myFragment;

    private long backPressed;
    private AlertDialog exitDialog;
    private boolean isRunGetNotice;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // 保存tab选中的状态״̬
        outState.putInt(TAB_SELECTED, indexSelected);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        if(spManager.islogin()) {
            if (spManager.needShowNoBaopei()) {
                ivBack.setVisibility(View.VISIBLE);
            } else {
                ivBack.setVisibility(View.GONE);
            }
        }else{
            ivBack.setVisibility(View.VISIBLE);
        }

        initTab();
        initFragment(savedInstanceState);
        HttpManager.getInstance(this).getUserInfo(this);
        EventBus.getDefault().register(this);
        if (spManager.isInit() && !spManager.islogin()) {
            /**
             * 第一次安装完打开，显示新手指引
             */
            SysUnits sysUnits = (SysUnits) aCache.getAsObject(Constant.CACHE_NEW_GUIDE_PIC);
            if (sysUnits != null) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constant.EXTRA_AD, sysUnits);
                bundle.putBoolean(Constant.EXTRA_NEW_USER, true);
                intentTo(AdActivity.class, bundle);
                spManager.setInit(false);
            }
        } else {
            /**
             * 悬浮广告
             */
            if (!Utils.isEmpty(spManager.getSuspensionAd()))
                HttpManager.getInstance(this).getSuspensionAd(spManager.getSuspensionAd(), this);
        }
        HttpManager.getInstance(this).getOrderBroadcast(this);//系统公告
        HttpManager.getInstance(this).getIsShowBcak(this);//系统公告
        getDefaultHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                UpdateManager.getInstance().checkUpdate(MainActivity.this,false);
            }
        }, 2000);
        TrackingIO.initWithKeyAndChannelId(getApplicationContext(), Constant.TRACKING_KEY, Utils.getChannel(this));
    }

    private void initTab() {
        indexSelected = getIntent().getIntExtra(Constant.EXTRA_TAB_INDEX, 0);
        tabIndex.setTextAndDrawableTop(R.string.index,
                R.drawable.tab_index);
        tabNews.setTextAndDrawableTop(R.string.news,
                R.drawable.tab_news);
        tabGoods.setTextAndDrawableTop(R.string.goods, R.drawable.tab_goods);
        tabMy.setTextAndDrawableTop(R.string.my_center, R.drawable.tab_my);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int tabIndex = intent.getIntExtra(Constant.EXTRA_TAB_INDEX, -1);
        if (tabIndex > -1) {
            tabPerformClick(tabIndex);
        }
    }

    private void initFragment(Bundle savedInstanceState) {
        fragmentManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            // 读取上一次界面Save时候tab选中的状态״̬
            indexSelected = savedInstanceState.getInt(TAB_SELECTED,
                    indexSelected);
            indexFragment = (IndexFragment) fragmentManager
                    .findFragmentByTag(FRAGMENT_TAG[0]);
            newsFragment = (NewsFragment) fragmentManager
                    .findFragmentByTag(FRAGMENT_TAG[1]);
            goodsFragment = (GoodsFragment) fragmentManager
                    .findFragmentByTag(FRAGMENT_TAG[2]);
            myFragment = (MyFragment) fragmentManager
                    .findFragmentByTag(FRAGMENT_TAG[3]);
            FragmentTransaction transaction = fragmentManager
                    .beginTransaction();
            if (indexFragment != null)
                transaction.hide(indexFragment);
            if (newsFragment != null)
                transaction.hide(newsFragment);
            if (goodsFragment != null)
                transaction.hide(goodsFragment);
            if (myFragment != null)
                transaction.hide(myFragment);
            transaction.commitAllowingStateLoss();

        } else {
            indexSelected = 0;
        }
        tabPerformClick(indexSelected);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    /**
     * 自动点击指定的TAB
     *
     * @param index TAB下标
     */
    private void tabPerformClick(int index) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (index) {
            case TAB_INDEX:
                switchTab(tabIndex, TAB_INDEX);
                if (indexFragment == null) {
                    indexFragment = new IndexFragment();
                    transaction.add(R.id.fragment, indexFragment,
                            IndexFragment.class.getSimpleName());
                } else {
                    transaction.show(indexFragment);
                }
                if (indexSelected != TAB_INDEX) {
                    // 隐藏上次展示的fragment
                    transaction.hide(fragmentManager
                            .findFragmentByTag(FRAGMENT_TAG[indexSelected]));
                    lastClickTime = 0;
                } else {
                    if (lastClickTime != 0) {
                        if (System.currentTimeMillis() - lastClickTime <= 500) {
                            lastClickTime = 0;
//                            indexFragment.setRefresh();
                        } else {
                            lastClickTime = System.currentTimeMillis();
                        }
                    } else {
                        lastClickTime = System.currentTimeMillis();
                    }
                }
                transaction.commitAllowingStateLoss();
                // 更新当前展示的下标
                indexSelected = TAB_INDEX;
                break;
            case TAB_NEWS:
                switchTab(tabNews, TAB_NEWS);
                if (newsFragment == null) {
                    newsFragment = new NewsFragment();
                    transaction.add(R.id.fragment, newsFragment,
                            NewsFragment.class.getSimpleName());
                } else {
                    transaction.show(newsFragment);
                }
                if (indexSelected != TAB_NEWS) {
                    // 隐藏上次展示的fragment
                    transaction.hide(fragmentManager
                            .findFragmentByTag(FRAGMENT_TAG[indexSelected]));
                    lastClickTime = 0;
                } else {
                    if (lastClickTime != 0) {
                        if (System.currentTimeMillis() - lastClickTime <= 500) {
                            lastClickTime = 0;
//                            newsFragment.setRefresh();
                        } else {
                            lastClickTime = System.currentTimeMillis();
                        }
                    } else {
                        lastClickTime = System.currentTimeMillis();
                    }
                }
                transaction.commitAllowingStateLoss();
                // 更新当前展示的下标
                indexSelected = TAB_NEWS;
                break;
            case TAB_GOODS:
                switchTab(tabGoods, TAB_GOODS);
                if (goodsFragment == null) {
                    goodsFragment = new GoodsFragment();
                    transaction.add(R.id.fragment, goodsFragment,
                            GoodsFragment.class.getSimpleName());
                } else {
                    transaction.show(goodsFragment);
                }
                if (indexSelected != TAB_GOODS) {
                    // 隐藏上次展示的fragment
                    transaction.hide(fragmentManager
                            .findFragmentByTag(FRAGMENT_TAG[indexSelected]));
                    lastClickTime = 0;
                } else {
                    if (lastClickTime != 0) {
                        if (System.currentTimeMillis() - lastClickTime <= 500) {
                            lastClickTime = 0;
//                            goodsFragment.setRefresh();
                        } else {
                            lastClickTime = System.currentTimeMillis();
                        }
                    } else {
                        lastClickTime = System.currentTimeMillis();
                    }
                }
                transaction.commitAllowingStateLoss();
                // 更新当前展示的下标
                indexSelected = TAB_GOODS;
                break;
            case TAB_MY:
                switchTab(tabMy, TAB_MY);
                if (myFragment == null) {
                    myFragment = new MyFragment();
                    transaction.add(R.id.fragment, myFragment,
                            MyFragment.class.getSimpleName());
                } else {
                    transaction.show(myFragment);
                }
                if (indexSelected != TAB_MY) {
                    // 隐藏上次展示的fragment
                    transaction.hide(fragmentManager
                            .findFragmentByTag(FRAGMENT_TAG[indexSelected]));
                    lastClickTime = 0;
                }
                transaction.commitAllowingStateLoss();
                // 更新当前展示的下标
                indexSelected = TAB_MY;
                break;
        }
    }

    private long lastClickTime;

    private void switchTab(View v, int index) {
        TabView tab = (TabView) v;
        tab.setTabCheck(true);
        if (lastTab != null && indexSelected != index) {
            lastTab.setTabCheck(false);
        }
        lastTab = tab;
    }

    @OnClick({R.id.tab_index, R.id.tab_news, R.id.tab_goods, R.id.tab_my, R.id.iv_ad})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab_index:
                tabPerformClick(TAB_INDEX);
                break;
            case R.id.tab_news:
                tabPerformClick(TAB_NEWS);
                break;
            case R.id.tab_goods:
                tabPerformClick(TAB_GOODS);
                break;
            case R.id.tab_my:
                if (isLogin)
                    tabPerformClick(TAB_MY);
                else {
                    intentTo(LoginActivity.class);
                }
                break;
            case R.id.iv_ad://不中包赔
                showProgressDialog();
                HttpManager.getInstance(this).getBackSale(this);
                break;
        }
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GET_USER_INFO:
                try {
                    if (result.getInt("errcode") == 0) {
                        spManager.setIsLogin(true);
                        ProfileInfo info = new Gson().fromJson(result.getJSONObject("data").toString(), ProfileInfo.class);
                        Map<String, Object> extra = new HashMap<>();
                        extra.put("_name",info.getName());
                        extra.put("_tel",info.getPhone());
                        TrackingIO.setProfile(extra);
                        spManager.setUserId(info.getId());
                        aCache.put(Constant.CACHE_KEY_PROFILE, info);
                        updateProfile(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_SUSPENSION_AD:
                try {
                    if (result.getInt("errcode") == 0) {
                        List<SysUnits> newAd = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<SysUnits>>() {
                        }.getType());
                        if (newAd != null && newAd.size() > 0) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(Constant.EXTRA_AD, newAd.get(0));
                            intentTo(AdActivity.class, bundle);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_ORDER_BROADCAST:
                try {
                    if (result.getInt("errcode") == 0) {
                        List<String> newNotices = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<String>>() {
                        }.getType());
                        EventBus.getDefault().postSticky(new NoticeDataEvent(newNotices));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_BACK_SALE:
                try {
                    if (result.getInt("errcode") == 0) {
                        intentTo(CompensationActivity.class);
                    } else {
                        showToastSafe(result);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_IS_SHOW_BACK:
                try {
                    if (result.getInt("errcode") == 0 && result.getInt("data") == 1) {
                        ivBack.setVisibility(View.VISIBLE);
                    } else {
                        ivBack.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ivBack.setVisibility(View.GONE);
                }
                break;
        }
    }


    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        switch (httpTag) {
            case TAG_GET_ORDER_BROADCAST:
                isRunGetNotice = false;
                getDefaultHandler().postDelayed(noticeRun, 20000);
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        getDefaultHandler().removeCallbacks(noticeRun);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!isRunGetNotice) {
            getDefaultHandler().removeCallbacks(noticeRun);
            getDefaultHandler().postDelayed(noticeRun, 20000);
        }
    }

    /**
     * 轮询系统公告接口
     */
    private Runnable noticeRun = new Runnable() {
        @Override
        public void run() {
            HttpManager.getInstance(MainActivity.this).getOrderBroadcast(MainActivity.this);
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoShoppingEvent(GoShoppingEvent event) {
        tabPerformClick(2);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoMyCenterEvent(TabIndexEvent event) {
        tabPerformClick(event.getIndex());
        if (event.isNewUser()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyDialog);
            builder.setTitle("提示");
            builder.setMessage("您已获赠5拍币，是否前往新手专区");
            builder.setPositiveButton("前往", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.EXTRA_TITLE, getString(R.string.new_guidelines));
                    bundle.putString(Constant.EXTRA_URL, UrlManager.H5_NEW_GUIDE);
                    intentTo(H5Activity.class, bundle);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.create().show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        getDefaultHandler().removeCallbacks(noticeRun);
        TrackingIO.exitSdk ();
    }

    @Override
    public void onBackPressed() {
//        showExitDialog();

        if (backPressed + 2000 > System.currentTimeMillis()) {
            super.onBackPressed();
        } else {
            showToastSafe(R.string.press_again_exit);
            backPressed = System.currentTimeMillis();
        }
    }

    private void showExitDialog() {
        if (exitDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyDialog);
            builder.setMessage(R.string.content_exit_dialog);
            builder.setNegativeButton(R.string.cancel, (dialog, which) -> exitDialog.dismiss());
            builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
                exitDialog.dismiss();
                finish();
            });
            exitDialog = builder.create();
        }
        exitDialog.show();
    }

}
